<?php	

	define('ChartType','Pie');
	
	if (isset($_POST['Category'])) {
		
		include_once('../../config.php'); 
		session_start();
		LinkDataBase();
		$Array_Field = FieldLocationGet($_POST['Category']);
				
		$Field = implode(", ",$Array_Field);
		//Find question.
		$sql = "select ".$_POST['filename'][0].".table_name AS table_name, item, total, ".$Field." 
				FROM ".$_POST['filename'][0]." LEFT JOIN sheet 
				ON ".$_POST['filename'][0].".table_name = binary(sheet.table_name) 
				WHERE table_number='".$_POST['tablename']."' AND 
				item NOT LIKE '%Base: All Respondents%' AND 
				item NOT LIKE '%Base: Respondents%'";
		
		$result= mysql_query($sql);
		$numResult = mysql_num_rows($result);
		
		if ($numResult > 0) {
		?>
                
			<script type="text/javascript">
			var sub_QAname = '';

			var myrow = new Array();
			var RowTitle = new Array();
			<?php
			
			$item = "";
			$index = 0;
			$z = 0;
			while($row = mysql_fetch_assoc($result)) {
				
				//Find Column name and define array.
				if ($row['total']=='Total') {
					$tablename = $row['table_name'];
					for ($i=0; $i<count($Array_Field); $i++) {
					?>
						var DB_title = '<?php echo $row[$Array_Field[$i]];?>';
						console.log(DB_title);
						RowTitle.push(DB_title);
					<?php
					}
				}
				
				
				if ((($item!="")&&($row['item']!='Sigma')&&
					(strpos($row['total'],'%'))&&
					($_POST['keyword']==''))||
					//For keyword exists.
					(($item!="")&&($row['item']!='Sigma')&&
					(strpos($row['total'],'%'))&&
					($_POST['keyword']!='')&&
					//contain is YES.
					(((strpos($item,(string)$_POST['keyword']))&&
					($_POST['contain']=='YES'))||
					//contain is NO.
					((!strpos($item,(string)$_POST['keyword']))&&
					($_POST['contain']=='NO'))))) {
						
						
						
					//Check type and Catch next question info for javascript.
					if (isset($_POST['Array_SubXML']['sub_QAname'])) {
						if (is_array($_POST['Array_SubXML']['sub_QAname'])) {
						?>
							sub_QAname = '<?php echo $_POST['Array_SubXML']['sub_QAname'][$index]; ?>\n';
						<?php
							$index++;
						}
						else {
						?>
							sub_QAname = '<?php echo $_POST['Array_SubXML']['sub_QAname']; ?>\n';
						<?php
						}
					}
					?>
					var index = <?php echo $z;?>;
					myrow[index] = new Array();
					
					var ItemName = '<?php echo str_replace("'","\'",str_replace('(Net)','',$item)); ?>';
					
					if ((ItemName!='No')&&(sub_QAname!=''))
						ItemName = ItemName+sub_QAname;
					
					myrow[index].push(ItemName);
					<?php
					for ($i=0; $i<count($Array_Field); $i++) {
						
						//Check row is percent or not percent.
						if (strpos($row[$Array_Field[$i]], '%')!==false)
							$value = str_replace('%','',$row[$Array_Field[$i]])/100;
						else
							$value = '0.00';
						
					?>
						var value = <?php echo $value; ?>;
						myrow[index].push(value);
						myrow[index].push(sub_QAname+Math.round(value*100)+'%');
					<?php
					}
					$z++;
				}
				else if ($row['item']=='Sigma')
					break;
							
				$item = $row['item'];
			}
			?>
			var Array_Chart = new Array();
			<?php
			for ($i=0; $i<count($Array_Field); $i++) {
			?>
				var index = <?php echo $i;?>;
				
				var data = new google.visualization.DataTable();
  				data.addColumn('string');
				data.addColumn('number');
				data.addColumn({type: 'string', role: 'tooltip'});
				for (var i=0; i<myrow.length; i++)
					data.addRow([myrow[i][0],myrow[i][1+index*2],myrow[i][2+index*2]]);
				
				
				
				var options = {
				title: RowTitle[index],	
				legend: {position: 'none'},
				vAxis: {textPosition:'out', maxValue:1, minValue:0, format:'#%'},
				height: '100%',
				tooltip: {text: 'percentage', showColorCode: 'true'}
				};
					
				Array_Chart[index] = new google.visualization.PieChart(document.getElementById('chart_div<?php echo $i; ?>'));
				Array_Chart[index].draw(data, options);
				
				if (sub_QAname!='') {	
					//Handle event.
					google.visualization.events.addListener(Array_Chart[index], 'select', selectHandler(data, Array_Chart[index]));
				}
				
			<?php
			}
			?>
			
			function selectHandler(data, chart) {
				return function(){
					//Check type and Catch next question info for javascript.
					var sub_ChartType = '';
					var KeyWord = '';
					var Contain = '';
					
					var selection = chart.getSelection();
					var message = selection[0];
					
					//if cancel selection, Stop crash.
					if (message==null)
						return;
					
					console.log(data);
       	 			var str = data['La'][message.row][0]['Rh'];
					
					//Stop that select No, click to next question.
					if (str=='No')
						return;	
							
					<?php
					if (isset($_POST['Array_SubXML']['sub_table'])) {
						if (is_array($_POST['Array_SubXML']['sub_table'])) {
					?>
							var selection = chart.getSelection();
							var message = selection[0];
							var index = message.row;
							var Temp_Array_Table = <?php echo json_encode($_POST['Array_SubXML']['sub_table']); ?>;
							var Temp_Array_ChartType = <?php echo json_encode($_POST['Array_SubXML']['sub_charttype']); ?>;
							var Temp_Array_KeyWord = <?php echo json_encode($_POST['Array_SubXML']['sub_keyword']); ?>;
							var Temp_Array_Contain = <?php echo json_encode($_POST['Array_SubXML']['sub_contain']); ?>;
	
							sub_table = Temp_Array_Table[index];
							sub_ChartType = Temp_Array_ChartType[index];
							KeyWord = Temp_Array_KeyWord[index];
							Contain = Temp_Array_Contain[index];
					<?php
						}
						else {
					?>
							sub_table = '<?php echo $_POST['Array_SubXML']['sub_table']; ?>';
							sub_ChartType = '<?php echo $_POST['Array_SubXML']['sub_charttype']; ?>';
							KeyWord = '<?php echo $_POST['Array_SubXML']['sub_keyword']; ?>';
							Contain = '<?php echo $_POST['Array_SubXML']['sub_contain']; ?>';
					<?php
						}
					}
					?>
						
					var year = '<?php echo $_POST['year']; ?>';
					var season = '<?php echo $_POST['season']; ?>';
					var Step = <?php echo $_POST['step']; ?>;
						
					//Check previous title is array or string.
					var Previous_Title = new Array();
					<?php
					if (is_array($_POST['previous_title'])) {
					?>
						Previous_Title = <?php echo json_encode($_POST['previous_title']); ?>;
					<?php
					}
					else {
					?>
						Previous_Title.push('<?php echo $_POST['previous_title']; ?>');
					<?php
					}
					?>
					var Temp = new Array('<?php echo '<a href="#" id="'.$_POST['step'].'" class="'.ChartType.'" onclick="GotoTargetLocation(this);" >'.$_POST['tablename'].'</a>'; ?>',
					'<?php echo $_POST['tablename']; ?>','<?php echo ChartType; ?>', '<?php echo $_POST['keyword']; ?>', '<?php echo $_POST['contain']; ?>');
					Previous_Title.push(Temp);
					
					$("#content-detail").load('../chart/detail/index.php',
					{'year':year, 'season':season, 'tablename': sub_table, 'charttype': sub_ChartType, 
					'keyword': KeyWord, 'contain': Contain, 'step': Step+1, 'previous_title': Previous_Title});
				}
			}
			
			//Created Legend.
			var data = new google.visualization.DataTable();
  			data.addColumn('string','Area');
				
			var Array_Legend = new Array('');
			for (var i=0; i<myrow.length; i++) {
				data.addColumn('number',myrow[i][0]);
				Array_Legend.push(1);
			}
			data.addRow(Array_Legend);
			var Height_Legend = (data.getNumberOfColumns()-1)*20;
			var options_legend = {
				chartArea :{width: 0, height:Height_Legend},
				legend: {position: 'right', textStyle: {color: 'blue', fontSize: 12}},
				hAxis: {textPosition:'none'},
				vAxis: {textPosition:'none'},
				height: Height_Legend
			};
			
			var chart_Legend = new google.visualization.BarChart(document.getElementById('legend_div'));
			chart_Legend.draw(data, options_legend);
			
         </script>
<?php
		}
	}
	
	//Created chart frame by count of category.
	for ($i=1; $i<count($Array_Field)+1; $i++) {
		
		if ($i%2===0) {
			$ClassName = 'tablegeneric';
			$CSSLocation = 'padding: 0 20px 0 20px';
			$addFrontHtml = '';
			$addBackHtml = '</tr>';
		}
		else {
			$ClassName = 'tablegenericleft'; 
			$CSSLocation = 'margin-left: 0px';
			$addFrontHtml = '<tr>';
			$addBackHtml = '';
		}
		$table .= $addFrontHtml.'<td><table width="300" border="1" cellspacing="0" cellpadding="0" class="'.$ClassName.'" style="'.$CSSLocation.'">
<div id="chart_div'.($i-1).'" style="width: 400; height:200"></div></table></td>'.$addBackHtml;
	}
	
?>
<div class="right-image">
<table>

 <?php echo $table; ?>

</table>
</div><br/>
<div id="legend_div" style="width: 770;margin-bottom:30px;" class="right-image"></div>